package cn.vihub.controller;

import cn.hutool.crypto.SecureUtil;
import cn.vihub.client.user.UserFeignClient;
import cn.vihub.handler.MyRuntimeException;
import cn.vihub.param.ShopUserParam;
import cn.vihub.param.TokenParam;
import cn.vihub.pojo.ShopUser;
import cn.vihub.service.TokenService;
import cn.vihub.utils.Result;
import cn.vihub.vo.TokenVo;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Author: 秋晚
 * @Date: 2025/7/20 17:44
 * @Description:
 **/
@RestController
@RequiredArgsConstructor
@RequestMapping("shop-auth/login")
public class LoginController {

    @Autowired
    TokenService tokenService;

    private final UserFeignClient userFeignClient;




    /**
     * @author: 秋晚
     * @description:登录获取token
     * @params: []
     * @return: cn.vihub.utils.Result<cn.vihub.vo.TokenVo>
     * @date: 2025/7/20 18:28
     */
    @PostMapping("getAccessToken")
    public Result<TokenVo> getAccessToken(@RequestBody ShopUserParam shopUserParam){
        //根据username查询
        //远程调用
        ShopUser shopUser = userFeignClient.getUserByUsername(shopUserParam.getUsername());
        if(shopUser==null){
            throw new MyRuntimeException("用户不存在!");
        }

        if(!shopUser.getPassword().equals(SecureUtil.md5(shopUserParam.getPassword()))){
            System.out.println(SecureUtil.md5(shopUserParam.getPassword()));
            throw new MyRuntimeException("密码错误!");
        }

        return Result.success(tokenService.createAccessToken(shopUser.getId(),shopUser.getUsername()));
    }

    /**
     * @author: 秋晚
     * @description:刷新短期token
     * @params: [cn.vihub.param.TokenParam]
     * @return: cn.vihub.utils.Result<cn.vihub.vo.TokenVo> 
     * @date: 2025/7/20 19:03
     */
    @PostMapping("getRefreshToken")
    public Result<TokenVo> getRefreshToken(@RequestBody TokenParam tokenParam){
        return Result.success(tokenService.getRefreshToken(tokenParam.getRefreshToken()));
    }

}
